package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	"github.com/PuerkitoBio/goquery"
	"github.com/axgle/mahonia"
	"github.com/gin-gonic/gin"
	"github.com/saintfish/chardet"
)

func ConvertToString(src string, srcCode string, tagCode string) string {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(src)
	tagCoder := mahonia.NewDecoder(tagCode)
	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
	result := string(cdata)
	return result
}

func OpenHtmlFile(c *gin.Context) {
	filePath := c.Query("dir")
	file, err := os.Open(filePath)
	if err != nil {
		fmt.Println("open file err=", err)
	}

	//当函数退出时，要及时的关闭file
	defer file.Close() //要及时关闭file句柄，否则会有内存泄漏
	OldReader := bufio.NewReader(file)
	all, _ := ioutil.ReadAll(OldReader)
	detector := chardet.NewTextDetector()
	charset, err := detector.DetectBest(all[:128])
	if err != nil {
		panic(err)
	}

	fmt.Println(charset.Charset)
	targetString := ConvertToString(string(all[:]), charset.Charset, "utf-8")
	if strings.HasPrefix(charset.Charset, "ISO") || strings.HasPrefix(charset.Charset, "iso") {
		targetString = ConvertToString(string(all[:]), "GBK", "utf-8")
	}

	dom, _ := goquery.NewDocumentFromReader(strings.NewReader(targetString))

	dom.Find("title").Each(func(i int, s *goquery.Selection) {
		fmt.Println("i", i, "选中的文本", s.Text())
	})
	dom.Find("title").AfterHtml(`<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />`)
	dom.Find("body").PrependHtml(`<div><p><a href="/command/saveFile?path=` + filePath + `">保存</a></p></div>`)
	outHtml, _ := dom.Html()
	ioutil.WriteFile("./templates/out.html", []byte(outHtml), 0777)
	c.HTML(http.StatusOK, "out.html", nil)
}

func BuildFileSystemMapping(engine *gin.Engine) {
	commandList := engine.Group("/file")
	commandList.GET("/open/html", OpenHtmlFile)
}
